import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

# 获取部门（组织）树 对应界面 用户管理--组织信息
def doGetdepartmentList():
   try:
      logger.info('111:获取部门（组织）树');
      conn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      conn.request("GET", "/openapi/department/tree?options=8", payload, headers)
      res = conn.getresponse()
      data = res.read()
      # print(data.decode("utf-8"))
      logger.info('101:' + data.decode("utf-8"))
      conn.close()
   except Exception as e:
      logger.info('111:错误'+str(e));

# 新增或编辑部门接口2
def doSenddepartment(py_flag,py_no,py_dict):
    try:
        conn = http.client.HTTPSConnection(global_url)
        payload=json.dumps(py_dict)
        headers = {
            'app-id': global_appid,
            'app-key': global_appkey,
            'Content-Type': 'application/json'
        }
        conn.request("POST", "/openapi/department/added", payload, headers)
        res = conn.getresponse()
        data = res.read()
        data = data.decode("utf-8")
        # print(data.decode("utf-8"))
        logger.info('113:' + data)
        conn.close()

        if (py_flag == 2):
            print("修改")
        else:
            # 新增 依据返回值刷新id
            json_str = json.loads(data)
            ierrCode = json_str["errCode"]
            if (ierrCode == 200):
                data_json = json_str["data"]
                id = data_json["id"]
                # print(id, end="\n")
                sql = "update a_ts_department  set ferp_load=NOW()"
                sql = sql + ",ferp_id=" + str(id)
                sql = sql + " where fdep_no='" + py_no + "'"
                sql = sql + " and fsite_no='" + global_site + "';"
                # print(sql)
                conn, cursor = postsql_utility.get_conn()
                i = postsql_utility.execute(sql=sql, cursor=cursor, connect=conn)
                if i != "OK":
                    print("失败" + str(i))
                else:
                    print("成功" + str(i))

    except Exception as e:
        logger.info('113:错误'+str(e))

# 新增或编辑部门接口
def doAdddepartment():
   try:
      logger.info('112:新增或编辑部门接口')
      # payload = json.dumps({
      #    "id": 104,
      #    "name": "实验室2d",
      #    "parentId": 101
      # })
      sql = "select fdep_no,fdep_name,fparent_no"
      sql = sql +" from a_ts_department"
      sql = sql +" where 1=1"
      sql = sql +" and fsite_no='"+global_site+"'"
      sql = sql +" and ((ferp_id is null) or (ferp_id=0))"
      sql = sql +" order by fdep_no;"
      logger.info('112:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data = postsql_utility.select(sql=sql, cursor=cursor)

      for j1 in range(len(data)):
          data_dict = {}
          #data_dict["id"] = int(data[j1][0])
          data_dict["name"] = data[j1][1]
          #data_dict["parentId"] = int(data[j1][2])
          #print(data_dict)
          doSenddepartment(1,data[j1][0],data_dict)

   except Exception as e:
      logger.info('112:错误'+str(e))

#直接调试
#doAdddepartment()